package com.demo.common.kit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 获取经纬度
 * 
 * @author jueyue 返回格式：Map<String,Object> map map.put("status",
 *         reader.nextString());//状态 map.put("result", list);//查询结果
 *         list<map<String,String>> 密钥:9VzDl66i4gz1kXMFqVVVp4Yugltk9HbP
 */
public class MapBaidu {
	private static final String BAIDUAK = "9VzDl66i4gz1kXMFqVVVp4Yugltk9HbP";

	public static Map<String, Double> getLngAndLat(String address) {
		Map<String, Double> map = new HashMap<String, Double>();
		String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + BAIDUAK;
		String json = loadJSON(url);
		JSONObject obj = JSON.parseObject(json);
		if (obj.get("status").toString().equals("0")) {
			double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
			double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
			map.put("lng", lng);
			map.put("lat", lat);
		} else {
			//LogKit.info("未查找到【" + address + "】的经纬坐标");
		}
		return map;
	}
	
	/**
	 * @Description: 根据经纬度获取用户的位置 
	 * @param lat
	 * @param lng
	 * @return
	 */
	public static String getAddress(double lat, double lng) {
		String url = "http://api.map.baidu.com/geocoder/v2/?location="+lat+","+lng+"&output=json&pois=1&ak="+BAIDUAK;
		String json = loadJSON(url);
		JSONObject obj = JSON.parseObject(json);
		if (obj.get("status").toString().equals("0")) {
//			LogKit.info(obj.getJSONObject("result").toJSONString());
			return obj.getJSONObject("result").getString("formatted_address");
		} else {
			//LogKit.info("未查找到用户具体位置信息");
		}
		return null;
	}
	
	public static String getCityName(double lat, double lng) {
		String url = "http://api.map.baidu.com/geocoder/v2/?location="+lat+","+lng+"&output=json&pois=1&ak="+BAIDUAK;
		String json = loadJSON(url);
		JSONObject obj = JSON.parseObject(json);
		if (obj != null && "0".equals(obj.get("status").toString())) {
//			LogKit.info(obj.getJSONObject("result").toJSONString());
			return obj.getJSONObject("result").getJSONObject("addressComponent").getString("city");
		} else {
			//LogKit.info("未查找到用户具体位置信息");
		}
		return null;
	}

	public static String loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return json.toString();
	}

}
